<template>
  <div class="bgc-default pad-20" v-loading="listLoading" element-loading-text="加载中">
    
    <!-- 平台类型 -->
    <third-platform-head :showTaoBaoIcon="false"
      :showTmallIcon="false"
      @platformTypeChange="platformTypeChange">
    </third-platform-head>

    <div class="bg-color-white mar-t-15 pad-l-20 pad-r-20 pad-t-20">
      <!-- 店铺块 -->
      <div>
        <label>选择店铺：</label>
        <el-select v-model="selectedShopId" placeholder="选择店铺" @change="doChangeShop">
          <el-option v-for="item in shopList" 
            :key="item.shopId" 
            :label="item.shopName" 
            :value="item.shopId">
          </el-option>
        </el-select>
      </div>

      <!-- tab块 -->
      <div class="tab-style-default">
        <el-tabs v-model="selectedType" @tab-click="doChangeTab">
          <el-tab-pane label="可选商品" name="0"></el-tab-pane>
          <el-tab-pane label="已选商品" name="1"></el-tab-pane>
        </el-tabs>
      </div>

      <!--顶部搜索 -->
      <div class="top-operate pad-l-10 pad-r-10">
        <!-- 第一行 -->
        <div v-if="selectedType === '1'" class="mar-b-10">
          <div class="inline-flex">
            <span>操作结果：</span>
            <el-select v-model="defaultQuery.updateStatus" class="width-120" clearable>
              <el-option key="成功" label="成功" value="1"></el-option>
              <el-option key="失败" label="失败" value="2"></el-option>
            </el-select>
          </div>
          <div class="inline-flex">
            <span class="mar-l-20">上下架状态：</span>
            <el-select v-model="goodsStatusModel" class="width-150" clearable>
              <el-option key="下架" label="下架" value="0"></el-option>
              <el-option key="上架" label="上架" value="1"></el-option>
            </el-select>
          </div>
        </div>
        <!-- 第二行 -->
        <div>
          <div class="inline-flex">
            <span>搜索：</span>
            <el-select v-model="textCol" class="width-120">
              <el-option label="商品名称" value="title"></el-option>
            </el-select>
            <el-input v-model="textValue" placeholder="请输入内容" class="width-200"></el-input>
          </div>
          <div class="inline-flex">
            <span class="mar-l-20">商品分类：</span>
            <el-cascader v-model="categoryIds" 
              :props="{ checkStrictly: true }" 
              :options="categoryData" 
              class="width-300"
              clearable>
            </el-cascader>
          </div>
          <el-button-group class="mar-l-20">
            <el-button type="primary" @click="doSearch">查询</el-button>
            <el-button plain @click="doResetSearch">重置</el-button>
          </el-button-group>
          <el-button class="mar-l-10" @click="doExport()">导出</el-button>
        </div>
      </div>

      <!-- 按钮块 -->
      <div class="pad-b-15 v-align-c">
        <el-checkbox class="mar-l-14 mar-r-0" v-model="allChecked" @change="selectAll"><span class="mar-l-20">当页全选</span></el-checkbox>
        <span class="pad-l-4 pad-r-4">|</span>
        <div class="width-80">已选{{multipleSelection.length}}项</div>

        <template v-if="selectedType === '0'">
          <el-button @click="addGoodsJoinShop()">加入店铺</el-button>
        </template>
        <template v-else>
          <el-button @click="doOperationGoods(null, 'update')">更新商品信息</el-button>
          <el-button @click="doOperationGoods(null, 'delete')">移出店铺</el-button>
          <el-button @click="doOperationGoods(null, 'invalid')">移除失效商品</el-button>
        </template>
      </div>

      <!-- 内容列表 -->
      <div class="table-container">
        <el-table :data="dataList" ref="multipleTable" @selection-change="handleSelectionChange">
          <el-table-column width="55px" type="selection"></el-table-column>
          <el-table-column width="280px" label="商品名称" fixed="left">
            <template slot-scope="scope">
              <div class="flex v-align-c cursor-p">
                <label><img :src="scope.row.imageUrl" class="t-goods-pic"></label>
                <div class="font-14 pad-l-10 v-align-h height-65">
                  <div class="goods-title" @click="doLinkDetail(scope.row)">
                    <div class="line-2">
                      <template v-if="scope.row.categoryName">
                        <el-tag size="mini" v-if="scope.row.skuFlag == 1" type="danger" effect="light">多</el-tag>
                      </template>
                      <span>{{scope.row.title}}</span>
                    </div>
                  </div>
                  <template v-if="scope.row.categoryName">
                    <span class="font-color-6 font-13">[{{scope.row.categoryName}}]</span>
                  </template>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="批发价" prop="wholesalePrice" v-if="getMemberId()"></el-table-column>
          <el-table-column label="零售价" prop="sellPrice">
            <template slot-scope="scope">
              <div>
                <span v-if="scope.row.minPrice">￥{{ scope.row.minPrice }} ~ ￥ {{ scope.row.maxPrice }}</span>
                <span v-else>{{ scope.row.sellPrice ? '￥' + scope.row.sellPrice : ''}}</span>
              </div>
            </template>
          </el-table-column>
          <template v-if="selectedType === '1'">
            <el-table-column label="状态">
              <template slot-scope="scope">
                <span v-if="scope.row.goodsStatus === 1">已上架</span>
                <span v-if="scope.row.goodsStatus === 0">已下架</span>
              </template>
            </el-table-column>
          </template>
          <el-table-column label="操作结果" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.updateStatus === 1">成功</span>
              <template v-if="scope.row.updateStatus === 2">
                <span>失败</span>
                <br />
                <span class="line-2" :title="scope.row.errorRemark">{{ scope.row.errorRemark }}</span>
              </template>
            </template>
          </el-table-column>
          <el-table-column width="120px" label="操作" align="right" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" size="medium" class="table-btn" @click="doLinkDetail(scope.row)">商品详情</el-button>
              <el-button type="text" size="medium" class="table-btn" @click="doSetProperty(scope.row)">设置商品属性</el-button>
              <el-button type="text" size="medium" class="table-btn" @click="addGoodsJoinShop(scope.row.goodsId)" v-if="selectedType === '0'">加入店铺</el-button>
              <!-- <el-button type="text" size="medium" class="table-btn" @click="doRenewGoodMaterial(scope.row)" v-if="platformType == 1">更新素材</el-button>
              <el-button type="text" size="medium" class="table-btn" @click="doSetDouYinMaterialProperty(scope.row)" v-if="platformType == 1">查看素材</el-button> -->
              <el-button type="text" size="medium" class="table-btn" @click="doOperationGoods(scope.row.thirdGoodsId, 'delete')" v-if="selectedType === '1'">移出店铺</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 列表分页 -->
      <div class="pagination">
        <el-pagination background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchListQuery.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="searchListQuery.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>

    <!-- 商品只读详情dialog -->
    <el-dialog title="商品详情" :visible.sync="goodsDetailVisible" top="5vh" width="1200px">
      <goods-read-only-detail :showFlag="goodsDetailVisible" 
        :goodsId="selectedRow.goodsId" 
        @callback="goodsDetailVisible = false">
      </goods-read-only-detail>
    </el-dialog>

    <!-- 素材列表dialog -->
    <el-dialog title="素材列表" :visible.sync="douYinMaterialVisible" width="900px">
       <dou-yin-material-property :showFlag="douYinMaterialVisible"
       :shopId="selectedShopId" 
       :goodsObj="selectedRow"
       @callback="doCallbackDouYinMaterialProperty">
       </dou-yin-material-property>
    </el-dialog>

    <!-- 商品属性dialog -->
    <el-dialog title="设置商品属性" :visible.sync="propertyVisible" width="530px">
      <goods-property v-if="!propertyHiddenFlag" :showFlag="propertyVisible" 
        :platformType="platformType" 
        :shopId="selectedShopId" 
        :goodsObj="selectedRow" 
        @callback="doCallbackProperty">
      </goods-property>
    </el-dialog>

  </div>
</template>

<script>
  import { getDictByGroupName } from '@/api/common/common'
  import { listThirdShop } from '@/api/user/third-shop'
  import { listGoodsCategory } from '@/api/goods/goods'
  import { renewGoodMaterial } from '@/api/goods/goodsMaterial'
  import {
    exportProjectGoods,
    pagingThirdGoods
  } from '@/api/third/thirdGoods'
  
  import thirdAuth from '../components/third-auth'
  import thirdPlatformHead from '../components/third-platform-head'
  import goodsReadOnlyDetail from '@/views/goods/components/goods-read-only-detail'
  import goodsProperty from './components/goods-property'
  import douYinMaterialProperty from './components/dou-yin-material-property'

  export default {
    components: {
      thirdPlatformHead,
      goodsReadOnlyDetail,
      goodsProperty,
      douYinMaterialProperty
    },
    mixins: [thirdAuth],
    data() {
      return {
        // 文本model
        textCol: 'title',
        textValue: '',
        // 商品状态model
        goodsStatusModel: '',
        // 默认条件
        defaultQuery: {
          currentPage: 1,
          size: 10,
          enterpriseId: '',
          memberId: '',
          updateStatus: ''
        },
        // 查询条件
        searchListQuery: {},
        // 数据字典
        dict: {
          platformType: {}
        },
        // 店铺id
        selectedShopId: '',
        // 选择类型
        selectedType: '0',
        // 平台类型
        platformType: 1,
        // 分类id集合
        categoryIds: [],
        // 分类集合
        categoryData: [],
        // 店铺集合
        shopList: [],
        total: 0,
        dataList: [],
        multipleSelection: [],
        listLoading: false,
        allChecked: false,
        // 详情visible
        goodsDetailVisible: false,
        // 属性visible
        propertyVisible: false,
        // 属性hidden（平台切换时 销毁组件）
        propertyHiddenFlag: false,
        // 抖音素材visible
        douYinMaterialVisible: false,
        // 选中行
        selectedRow: {}
      }
    },
    // 初始化页面
    created() {
      Object.assign(this.searchListQuery, this.defaultQuery)
      // 获取类目
      listGoodsCategory(this.getEnterpriseId()).then(response => {
        this.categoryData = response.data
      })
      getDictByGroupName('ThirdOrderDTO.platformType').then(response => {
        Object.assign(this.dict, response.data)
      })
      this.initListThirdShop()
    },
    methods: {
      // 获取商品列表
      initList() {
        if (!this.selectedShopId) {
          this.dataList = []
          this.total = 0
          return
        }
        this.searchQuery()
        this.listLoading = true
        pagingThirdGoods(this.searchListQuery).then(response => {
          if (response.isError) return
          this.total = response.data.total
          this.dataList = response.data.records
          this.listLoading = false
        })
      },
      // 平台类型切换事件
      platformTypeChange(platformType) {
        this.propertyHiddenFlag = true
        this.platformType = platformType
        this.selectedShopId = ''
        this.initListThirdShop()
      },
      // 店铺切换事件
      doChangeShop() {
        this.doResetSearch()
      },
      // tab切换事件
      doChangeTab() {
        this.searchListQuery.currentPage = 1
        this.doResetSearch()
      },
      // 获取第三方店铺列表
      initListThirdShop() {
        const params = {
          enterpriseId: this.getEnterpriseId(),
          memberId: this.getMemberId(),
          platformType: this.platformType
        }
        listThirdShop(params).then(response => {
          if (response.isError) return
          this.shopList = response.data
          if (response.data.length > 0) {
            this.selectedShopId = response.data[0].shopId
          }
          this.doResetSearch()
        })
      },
      // 设置查询条件
      searchQuery() {
        const size = this.searchListQuery.size
        const currentPage = this.searchListQuery.currentPage
        this.searchListQuery = { ... this.defaultQuery }
        this.searchListQuery.size = size
        this.searchListQuery.currentPage = currentPage

        const categoryIds = this.categoryIds
        this.searchListQuery.oneCategoryId = categoryIds.length > 0 ? categoryIds[0] : ''
        this.searchListQuery.twoCategoryId = categoryIds.length > 1 ? categoryIds[1] : ''
        this.searchListQuery.threeCategoryId = categoryIds.length > 2 ? categoryIds[2] : ''

        this.searchListQuery[this.textCol] = this.textValue
        this.searchListQuery.tiktokAuthority = this.platformType === 1 ? 1 : 0
        this.searchListQuery.quickAuthority = this.platformType === 2 ? 1 : 0
        this.searchListQuery.taobaoAuthority = this.platformType === 3 ? 1 : 0
        this.searchListQuery.pinDuoDuoAuthority = this.platformType === 4 ? 1 : 0
        this.searchListQuery.openAlibabaAuthority = this.platformType === 7 ? 1 : 0
        this.searchListQuery.shopId = this.selectedShopId
        this.searchListQuery.selectedType = this.selectedType
        this.searchListQuery.platformType = this.platformType

        if (this.searchListQuery.openAlibabaAuthority) {
          this.searchListQuery.wholesaleGoodsStatus = this.selectedType === '0' ? 1 : this.goodsStatusModel
        } else {
          this.searchListQuery.goodsStatus = this.selectedType === '0' ? 1 : this.goodsStatusModel
        }
        this.searchListQuery.enterpriseId = this.getEnterpriseId()
        this.searchListQuery.memberId = this.getMemberId()
      },
      // 查询事件
      doSearch() {
        this.searchListQuery.currentPage = 1
        this.initList()
      },
      // 重置事件
      doResetSearch() {
        const originData = this.$options.data()
        this.textCol = originData.textCol
        this.textValue = originData.textValue
        this.categoryIds = originData.categoryIds
        this.goodsStatusModel = originData.goodsStatusModel
        this.defaultQuery = originData.defaultQuery
        this.doSearch()
      },
      // 加入店铺事件
      addGoodsJoinShop(goodsId) {
        const goodsIds = []
        if (goodsId != null) {
          goodsIds.push(goodsId)
        } else {
          if (this.multipleSelection.length > 0) {
            this.multipleSelection.forEach(item => {
              goodsIds.push(item.goodsId)
            })
          } else {
            this.$message.error('请选择要操作数据')
            return
          }
        }
        const redirectUrl = '/#/' + (this.getMemberId() ? 'shop' : 'channel') + '/third-goods/index?platformType=' + this.platformType
        this.checkAccessToken(this.platformType, this.selectedShopId, redirectUrl, true).then(response => {
          if (response) {
            const platformName = this.dict.platformType[this.platformType]
            const msg = '将商品加入店铺，有可能会与通过' + platformName + '商家后台创建的商品重复，确定要添加商品？（建议不要在商家后台删除此处添加的商品，请使用“已选商品”中的移出店铺功能）'
            this.$confirm(msg, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              const params = {
                memberId: this.getMemberId(),
                shopId: this.selectedShopId,
                platformType: this.platformType,
                goodsIds: goodsIds
              }
              this.$bus.$emit('asyncHandle', '300008', params, () => {
                this.initList()
              })
            }).catch(() => {
              this.$message({ type: 'info', message: '已取消' })
            })
          }
        })
      },
      // 导出事件
      doExport() {
        if (!this.selectedShopId) {
          this.$message({ type: 'error', message: '请先选择店铺' })
          return
        }
        if (this.dataList.length <= 0) {
          this.$message({ type: 'warning', message: '暂无可导出数据' })
          return
        }
        this.searchQuery()
        const goodsIds = []
        if (this.multipleSelection.length > 0) {
          this.multipleSelection.forEach(item => {
            goodsIds.push(item.goodsId)
          })
        }
        this.searchListQuery['goodsIds'] = goodsIds
        window.open(exportProjectGoods(this.searchListQuery), '_blank')
      },
      // 操作商品
      doOperationGoods(thirdGoodsId, operationType) {
        let thirdGoodsIds = []
        if (thirdGoodsId != null) {
          thirdGoodsIds.push(thirdGoodsId)
        } else {
          if (this.multipleSelection.length <= 0) {
            this.$message.error('请选择要操作数据')
            return
          } else {
            thirdGoodsIds = this.multipleSelection.map(item => item.thirdGoodsId)
          }
        }
        const redirectUrl = '/#/shop/third-goods/index?platformType=' + this.platformType
        this.checkAccessToken(this.platformType, this.selectedShopId, redirectUrl, true).then(response => {
          if (response) {
            let hint
            switch (operationType) {
              case 'update':
                hint = '将所选商品信息更新至店铺，确定要更新？'
                break
              case 'delete':
                hint = '不再销售商品时，可将商品从店铺移出，确定要将选中的店铺商品移出？'
                break
              case 'invalid':
                hint = '点击“确定移除”，会将系统中已删除、不再发货的商品从店铺中移出，同时也无法再加入店铺。'
                break
              default:
                break
            }
            this.$confirm(hint, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              const params = {
                operationType: operationType,
                thirdGoodsIds: thirdGoodsIds
              }
              this.$bus.$emit('asyncHandle', '300009', params, () => {
                this.initList()
              })
            }).catch(() => {
              this.$message({ type: 'info', message: '已取消' })
            })
          }
        })
      },
      // 商品属性回调
      doCallbackProperty(callbackFlag, platformType) {
        if (callbackFlag) {
          this.initList()
        }
        this.selectedRow = {}
        this.propertyVisible = false
      },
      // 抖音商品素材属性回调
      doCallbackDouYinMaterialProperty(callbackFlag) {
        if (!callbackFlag) {
          this.selectedRow = {}
          this.douYinMaterialVisible = false
        }
      },
      // 查看详情事件
      doLinkDetail(row) {
        this.selectedRow = row
        this.goodsDetailVisible = true
      },
      // // 详情事件
      // doLinkDetail(row) {
      //   if (this.getMemberId()) return
      //   this.$router.push({ path: './detail/index', query: { goodsId: row.goodsId, shopId: this.selectedShopId, platformType: this.platformType, selectedType: this.selectedType, goodsSource: row.goodsSource, currentPage: this.searchListQuery.currentPage.toString() }})
      // },
      // 设置商品属性事件
      doSetProperty(row) {
        // this.selectedRow = row
        // this.propertyHiddenFlag = false
        // this.propertyVisible = true

        const routeData = this.$router.resolve({
          path: '/channel/third-goods/third-goods-property',
          query: {
            platformType: this.platformType,
            shopId: this.selectedShopId,
            goodsId: row.goodsId,
            thirdGoodsId: row.thirdGoodsId
          }
        })
        const newWindow = window.open(routeData.href, row.thirdGoodsId ? row.thirdGoodsId : (row.goodsId + this.platformType))
        newWindow.onload = () => (newWindow.document.title = row.title)
      },
      // 商品素材列表
      doSetDouYinMaterialProperty(row) {
        this.selectedRow = row
        this.douYinMaterialVisible = true
      },
      // 更新商品素材
      doRenewGoodMaterial(row) {
        this.$confirm('确定要更新素材吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          renewGoodMaterial(row.shopId, row.goodsId).then(response => {
            if (response.isError) return
            this.$message({
              message: response.msg,
              type: 'success'
            })
          })
        }).catch(() => {
          this.$message({ type: 'info', message: '已取消' })
        })
      },
      // 勾选事件
      handleSelectionChange(val) {
        this.multipleSelection = val
        if (this.multipleSelection.length === this.dataList.length) {
          this.allChecked = true
        } else {
          this.allChecked = false
        }
      },
      // 更改当前页数
      handleCurrentChange(val) {
        this.searchListQuery.currentPage = val
        this.initList()
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.searchListQuery.size = val
        this.initList()
      },
      selectAll() {
        if (this.multipleSelection.length === 0 || this.multipleSelection.length < this.dataList.length) {
          this.dataList.forEach(item => {
            this.$refs.multipleTable.toggleRowSelection(item, true)
          })
        } else {
          this.$refs.multipleTable.clearSelection()
        }
      }
    }
  }
</script>

<style lang="less" scoped>
  .table-container{
    /deep/.el-table th > .cell {
      padding-left: 14px;
    }
  }
  .goods-title {
    color: #155bd4;
    line-height: 1.2;
  }
</style>
